﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

namespace TouchInputManager.Tests
{
    [RequireComponent(typeof(Animator))]
    public class StructureDisperseAnimPlayer : StructureDispersePlayer, IAnimationClipSource
    {
        public AnimationClip disperseClip;
         
        protected PlayableGraph graph;

        protected AnimationPlayableOutput output;

        public override bool IsPlaying => graph.IsPlaying();
        
        private void OnDestroy()
        {
            graph.Destroy();
        }

        private void Start()
        {
            graph = PlayableGraph.Create();

            graph.SetTimeUpdateMode(DirectorUpdateMode.GameTime);
             
            output = AnimationPlayableOutput.Create(graph, "anim", GetComponent<Animator>());
        }

        public override IEnumerator PlayDisperseEffect()
        {
            if (IsPlaying)
                yield break;

            var clipPlayable = AnimationClipPlayable.Create(graph, disperseClip);

            clipPlayable.SetSpeed(1);

            clipPlayable.SetTime(0);

            output.SetSourcePlayable(clipPlayable);

            graph.Play();

            while (clipPlayable.GetTime() <= disperseClip.length)
            {
                yield return null;
            }

            graph.Stop();
        }

        public override IEnumerator PlayMergeEffect()
        {
            if (IsPlaying)
                yield break;

            var clipPlayable = AnimationClipPlayable.Create(graph, disperseClip);

            clipPlayable.SetSpeed(-1);

            clipPlayable.SetTime(clipPlayable.GetAnimationClip().length);

            output.SetSourcePlayable(clipPlayable);

            graph.Play();
            
            while (clipPlayable.GetTime() > 0)
            {
                yield return null;
            }

            graph.Stop();
        }

        public override IEnumerator StopEffect()
        {
            var clipPlayable = AnimationClipPlayable.Create(graph, disperseClip);

            clipPlayable.SetSpeed(-10000);

            clipPlayable.SetTime(0.1f);

            output.SetSourcePlayable(clipPlayable);

            graph.Play();

            while (clipPlayable.GetTime() > 0)
            {
                yield return null;
            }
            graph.Stop();
        }

        public void GetAnimationClips(List<AnimationClip> results)
        {
            if (disperseClip != null)
                results.Add(disperseClip);
        }
    }
}
